package gitlab

import (
	"errors"
	"github.com/AnonymousMister/go-gitlab-client/v2/gitlab"
	"gitlab-cli/db"
)

const (
	Def = "def"
)

type Client struct {
	Name     string `gorm:"primary_key;column:name;type:varchar(30)"`
	Url      string `gorm:"column:url;type:varchar(30)"`
	Token    string `gorm:"column:token;type:varchar(30)"`
	UserName string `gorm:"column:user_name;type:varchar(30)"`
}

func autoMigrate() {
	db.Db().AutoMigrate(&Client{})
}

var clientc = make(map[string]*gitlab.Gitlab)

func GitlabClient(name string) (*gitlab.Gitlab, error) {
	if clientc[name] != nil {
		return clientc[name], nil
	}
	autoMigrate()
	client := &Client{}
	if err := db.Db().Where("name = ?", name).First(client).Error; err != nil {
		return nil, err
	}
	gitlabc := gitlab.NewGitlab(client.Url, "", client.Token)
	clientc[name] = gitlabc
	return gitlabc, nil
}

func SaveClient(user *gitlab.User, token string, url string) error {
	client := &Client{
		UserName: user.Username,
		Token:    token,
		Url:      url,
		Name:     Def,
	}
	autoMigrate()
	clients := []Client{}
	if e := db.Db().Find(&clients).Error; e != nil {
		return e
	}
	if len(clients) > 0 {
		return errors.New("已经有登录的用户了 不能在登录了 直接操作吧！")
	}
	if e := db.Db().Save(client).Error; e != nil {
		return e
	}
	return nil
}
